package com.pzh.vue.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pzh.vue.common.Constants;
import com.pzh.vue.common.Result;
import com.pzh.vue.exception.ServiceException;
import com.pzh.vue.mapper.SysUserMapper;
import com.pzh.vue.pojo.SysUser;
import com.pzh.vue.pojo.dto.SysUserDto;
import com.pzh.vue.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
   private SysUserService sysUserService;
    @Autowired
   private SysUserMapper userMapper;
    /**
     * 查询所有用户
     * @return
     */
    @GetMapping
    public Result findAll(){
        List<SysUser> list = sysUserService.list();
        Result result=new Result();
        result.setStatus(200);
        result.setData(list);
        return result;
    }
    //新增修改用户
    @PostMapping(value = "/update")
    public Result saveUser(@RequestBody SysUser user){
        System.out.println(user);
        try {
            sysUserService.saveOrUpdate(user);
        }catch (Exception e){
            throw new ServiceException(Constants.CODE_500,"系统异常");
        }
        return Result.success();
    }
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,@RequestParam Integer pageSize,@RequestParam(defaultValue = "") String username){
        IPage<SysUser> page=new Page<SysUser>(pageNum,pageSize);
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        if (!(username==null)){
            queryWrapper.like("username",username);
        }
        try {
            sysUserService.page(page, queryWrapper);
        }catch (Exception e){
            throw new ServiceException(Constants.CODE_500,"系统异常");
        }
        return Result.success(page);
    }
    @PostMapping("/saveEvaluation")
    public Result saveEvaluation(@RequestBody SysUser user,@RequestParam String name){
        if ((userMapper.isEmptyCourse(name)==null)){
            return Result.error(Constants.CODE_1000,"错误！！！请先选课");
        }
      sysUserService.updateSelfEvaluation(user.getSelfEvaluation(),user.getUsername());
      return Result.success();
    }
    //增加和更新方法
    @PostMapping("/save")
    public boolean save(@RequestBody SysUser sysUser,String name) {
        //如果不是超级管理员不允许更新敏感信息
        if (!(sysUserService.checkRoot(name))){
            sysUser.setScores(null);
            sysUser.setRole(null);
        }

        QueryWrapper<SysUser> username = new QueryWrapper<SysUser>().eq("username", sysUser.getUsername());
        SysUser one = sysUserService.getOne(username,false);
        if (one==null){
            sysUser.setId(null);
        }
        else {sysUser.setId(one.getId());}
        boolean save = sysUserService.saveOrUpdate(sysUser);
        return save;
    }
    @RequestMapping("/scores")
    public Result selectScores(@RequestParam String username){
        String score = sysUserService.findScore(username);
        return Result.success(score);
    }
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        try {
            sysUserService.removeById(id);
        }catch (Exception e){
            throw new ServiceException(Constants.CODE_500,"系统异常");
        }
      return Result.success();
    }

    /**
     *excel导出
     * @param response
     * @throws IOException
     */
    @GetMapping("/export")
    public void exportExel(HttpServletResponse response) throws IOException {
        //查询所有用户
        List<SysUser> list=sysUserService.list();

        //在内存操作，写到浏览器
        ExcelWriter writer= ExcelUtil.getWriter(true);
        //默认配置
        writer.write(list,true);
        //设置content—type
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset:utf-8");
        //设置标题
        String fileName= URLEncoder.encode("用户信息","UTF-8");
        //Content-disposition是MIME协议的扩展，MIME协议指示MIME用户代理如何显示附加的文件。
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");
        ServletOutputStream outputStream= response.getOutputStream();
        //将Writer刷新到OutPut
        writer.flush(outputStream,true);
        outputStream.close();
        writer.close();
    }

    /**
     * 导入excel
     * @param file
     */
    @PostMapping("/import")
    public void importExcel(MultipartFile file) throws IOException {
        //1.第一种 头必须和实体一样
        //文件处理成io流
        InputStream in=file.getInputStream();
        //io流给ExcelReader
        ExcelReader excelReader=ExcelUtil.getReader(in);
        //读取数据且转化为list
        List<SysUser> list=excelReader.readAll(SysUser.class);
        //第二种导入方式
        //忽略第一行头
       /* List<List<Object>> list=excelReader.read(1);
        List<SysUser> listUser= CollUtil.newArrayList();
        for (List<Object> row: list) {
            SysUser user=new SysUser();
            user.setUsername(row.get(0).toString());
            *//*****类似一一对应*****//*
        }*/
        //批量注册进数据库
        sysUserService.saveBatch(list);
    }

    //用户登录
    @PostMapping("/login")
    public Result login(@RequestBody SysUserDto sysUserDto){
        log.info("登录");
        if (StringUtils.isEmpty(sysUserDto.getUsername())||StringUtils.isEmpty(sysUserDto.getPassword())){
          return Result.error(Constants.CODE_400,"参数非法");
        }
        SysUserDto login = sysUserService.login(sysUserDto);
        return Result.success(login);
    }
    @PutMapping("/register")
    public Result register(@RequestBody SysUserDto sysUserDto){
        if (StringUtils.isEmpty(sysUserDto.getUsername())||StringUtils.isEmpty(sysUserDto.getPassword())){
            return Result.error(Constants.CODE_400,"参数非法");
        }
        SysUserDto register = sysUserService.register(sysUserDto);
        return  Result.success(register);
    }

    /**
     * 根据名字查询个人信息
     * @param username
     * @return
     */
    @GetMapping("/person/{username}")
    public Result findPerson(@PathVariable String username){
        QueryWrapper<SysUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",username);
        SysUser person = sysUserService.getOne(queryWrapper);
        System.out.println(person);
        return Result.success(person);
    }
}
